// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)

Shader "Sprites/Blur/Default"
{
    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
        _Color ("Tint", Color) = (1,1,1,1)
        [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
        [HideInInspector] _RendererColor ("RendererColor", Color) = (1,1,1,1)
        [HideInInspector] _Flip ("Flip", Vector) = (1,1,1,1)
        [PerRendererData] _AlphaTex ("External Alpha", 2D) = "white" {}
        [PerRendererData] _EnableExternalAlpha ("Enable External Alpha", Float) = 0

        //因为shader取值都是百分比，所以我们要定出贴图的尺寸来进行计算
_TextureSize ("_TextureSize",Float) = 256
//取值半径
_BlurRadius ("_BlurRadius",Range(1,15) ) = 1
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Cull Off
        Lighting Off
        ZWrite Off
        Blend One OneMinusSrcAlpha

        Pass
        {
        CGPROGRAM
            #pragma vertex SpriteVert
            #pragma fragment SpriteFrag2
            #pragma target 2.0
            #pragma multi_compile_instancing
            #pragma multi_compile _ PIXELSNAP_ON
            #pragma multi_compile _ ETC1_EXTERNAL_ALPHA
            #include "UnitySprites.cginc"

        int _BlurRadius;
        float _TextureSize;
        
                    float4 GetBlurColor( float2 uv )
{

    float space = 1.0/_TextureSize; //算出一个像素的空间
    int count = _BlurRadius * 2 +1; //取值范围
    count *= count;

    //将以自己为中心，周围半径的所有颜色相加，然后除以总数，求得平均值
    float4 colorTmp = float4(0,0,0,0);
    for( int x = -_BlurRadius ; x <= _BlurRadius ; x++ )
    {
        for( int y = -_BlurRadius ; y <= _BlurRadius ; y++ )
        {
            float4 color = tex2D(_MainTex,uv + float2(x * space,y * space));
            colorTmp += color;
        }
    }
    return colorTmp/count;
}

fixed4 SampleSpriteTexture2 (float2 uv)
{
    fixed4 color = GetBlurColor(uv);//tex2D (_MainTex, uv);

#if ETC1_EXTERNAL_ALPHA
    fixed4 alpha = tex2D (_AlphaTex, uv);
    color.a = lerp (color.a, alpha.r, _EnableExternalAlpha);
#endif

    return color;
}

fixed4 SpriteFrag2(v2f IN) : SV_Target
{
    fixed4 c = SampleSpriteTexture2 (IN.texcoord) * IN.color;
    c.rgb *= c.a;
    return c;
}


        ENDCG
        }
    }
}
